package com.pearlsoft.rms.vcenter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.pearlsoft.rms.VmConstants;

/**
 * 
 * @author rainshow
 * @Created 2012-5-17 下午05:15:26
 */

@Service("vcenterConnectionManager")
public class VcenterConnectionManagerImpl implements VcenterConnectionManager {
    private static Log logger = LogFactory.getLog(VcenterConnectionManagerImpl.class);
    private long lastVisited = -1;
    private long timeout = 30 * 60 * 1000;
    private VcenterConnection connection;

    @Override
    public VcenterConnection getConnection() throws Exception {
        synchronized (VcenterConnectionManagerImpl.class) {
            if (System.currentTimeMillis() - lastVisited > timeout) {
                if (connection != null) {
                    logger.info("VCLOUD连接超时，重新连接。");
                }
                this.connection = new VcenterConnection(VmConstants.CENTER_URL, VmConstants.CENTER_USERNAME,
                        VmConstants.CENTER_PASSWORD);
                connection.connect();
            }
            this.lastVisited = System.currentTimeMillis();
        }
        return connection;
    }

}
